<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Value vs. Reference</title>
  <meta
 content="C++ Tutorial: Value vs. Reference"
 name="description" />
  <meta
 content="C++ Tutorial, Pass by Value vs. Pass by Reference, Call by Value vs. Call by Reference"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a>
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial -   Value vs. Reference</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br /><br />
<img src="images/valuevsreference/HamBakSan.png" alt="HamBakSan"/>
<br /><br />



<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="evaluation">Evaluation</div>
<p>The issue of <strong>value vs. reference</strong> is closely related to the rules for evaluating expressions in C++, especially for argument of functions. It's about when the arguments to a function are evaluated, when they are substituted into the function, and what form that substitution takes. </p>
<p>Let's take a look at one by one a little bit closer.</p>
<br />
<br />


<div class="subtitle" id="Callbyvalue">Call by value</div>
<p>
<strong>Call-by-value ( pass-by-value)</strong>  is the most common strategy of evaluation. In call-by-value, the argument expression is evaluated, and the resulting value is copied into corresponding variable in the function. If the function is able to assign values to its parameters, only its local copy is assigned. This means that anything passed into a function call is unchanged in the caller's scope when the function returns.</p>
<p>Here, we should be clear the term call-by-value. It is sometimes confusing because there
are people use the call-by-value where the value is a reference as in Java. So, in this tutorial, value is a value of a variable  as understood by the usual meaning of value. </p>

<br />
<br />


<div class="subtitle" id="Callbyreference">Call by reference</div>
<p><strong>call-by-reference (pass-by-reference)</strong> is the other strategy of evaluation. In the strategy,  a function receives an reference to the argument, rather than a copy of its value. </p>
<p>This typically means that the function can modify the argument. Because  arguments do not need to be copied, call-by-reference has the advantage of greater time- and space-efficiency as well as the potential for greater communication between a function and its caller since the function can return information using its reference arguments. However,  it has the disadvantage that a function must often take special steps to protect values it passes to the function.</p>
 C++ uses call-by-value as default, but offer special syntax for call-by-reference parameters. C++ additionally offers call-by-reference-to-const. </p>
<p>C support explicit reference such as pointer and this can be used to mimic call-by-reference. But in this case, a function's caller must explicitly generate the reference to supply as an argument.</p>
<br />
<br />


<div class="subtitle" id="variableswap">Variable Swap</div>
<p>Here is an example of showing the difference between <strong>call-by-value</strong> and <strong>call-by-reference</strong>
<pre>
#include &lt;iostream&gt;
using namespace std;

template&lt;class T&gt;
void swapVal(T obj1, T obj2) {
	T temp = obj1;
	obj1 = obj2;
	obj2 = temp;
}

template&lt;class T&gt;
void swapRef(T& obj1, T& obj2) {
	T temp = obj1;
	obj1 = obj2;
	obj2 = temp;
}

int main() 
{
	int a = 100, b = 200;
	cout << "Value:" << endl;
	cout << "1: a = " << a << " b = " << b << endl;
	<font color="blue">swapVal(a,b);</font>
	cout << "2: a = " << a << " b = " << b << endl;
	a = 300; b = 400;
	cout << endl;
	cout << "Reference:" << endl;
	cout << "1: a = " << a << " b = " << b << endl;
	<font color="blue">swapRef(a,b);</font>
	cout << "2: a = " << a << " b = " << b << endl;

	return 0;
}
</pre>
<p>The output is:</p>
<pre>
Value:
1: a = 100 b = 200
2: a = 100 b = 200

Reference:
1: a = 300 b = 400
2: a = 400 b = 300
</pre>
<p>As we see from the result, the swap in the <strong>swapValue()</strong> is just swapping the local values inside the function but not the values in the caller's scope.</p>
<br />
<br />


<div class="subtitle" id="classobjectswap">Class Object Swap</div>
<p>Here is an example swapping object of a class.</p>
<pre>
#include &lt;iostream&gt;
#include &lt;cstring&gt;

using namespace std;

template&lt;class T&gt;
void swapRef(T& obj1, T& obj2) {
	T temp = obj1;
	obj1 = obj2;
	obj2 = temp;
}

template&lt;class T&gt;
void swapVal(T obj1, T obj2) {
	T temp = obj1;
	obj1 = obj2;
	obj2 = temp;
}


class Bogo 
{
public:
	// default constructor
	Bogo (int i = 0, const char *s = "") {
		myInt = i;
		int len = strlen(s);
		<font color="blue">myString = new char[len+1];</font>
		strcpy(myString,s);	
	}

	// copy constructor overloading
	Bogo (const Bogo& b){
		int len = strlen(b.myString);
		<font color="blue">myString = new char[len + 1];</font>
		strcpy(myString,b.myString);
		myInt = b.myInt;
	}

	// copy assignment operator overloading
	Bogo operator=(const Bogo& b){
		int len = strlen(b.myString);
		<font color="blue">myString = new char[len + 1];</font>
		strcpy(myString,b.myString);
		myInt = b.myInt;
		return *this;
	}

	<font color="blue">friend ostream& operator<<(ostream & os, const Bogo & b);</font>

private:
	int myInt;
	char* myString;
};

<font color="blue">ostream & operator<<(ostream &os, const Bogo &b) {
	os << b.myInt << "," << b.myString ;
	return os;
}</font>

int main() 
{
	Bogo bogoA = Bogo(100,"AAA"); 
	Bogo bogoB = Bogo(200,"BBB");
	cout << "Value:" << endl;
	cout << "1: "<< bogoA << "   " << bogoB << endl; 
	<font color="blue">swapVal&lt;Bogo&gt;(bogoA,bogoB);</font>
	cout << "2: "<< bogoA << "   " << bogoB << endl; 

	cout << endl;

	bogoA = Bogo(100,"AAA"); 
	bogoB = Bogo(200,"BBB");
	cout << "Reference:" << endl;
	cout << "1: "<< bogoA << "   " << bogoB << endl; 
	<font color="blue">swapRef&lt;Bogo&gt;(bogoA,bogoB);</font>
	cout << "2: "<< bogoA << "   " << bogoB << endl; 

	return 0;
}
</pre>
<p>Note that we overloaded <strong>copy constructor</strong> and <strong>copy assignment operator</strong> to deal with the memory allocation by <strong>new</strong>. Also we overloaded the <strong>operator<<()</strong> to print out the object.</p>
<p>Here is the output:</p>
<pre>
Value:
1: 100,AAA   200,BBB
2: 100,AAA   200,BBB

Reference:
1: 100,AAA   200,BBB
2: 200,BBB   100,AAA
</pre>
<p>The output is almost similar to the case of swapping variables. Only the <strong>swapRef()</strong> did actually swap the objects.</p>
<br />
<br />


<div class="subtitle" id="valuevsreference">Prefer pass-by reference-to-const to pass-by-value</div>
<p>I intentionally used the Scott Meyers item.20 title of "Effective C++".</p>
<p>Here is the summary at the end of the section.</p>
<ol>
	<li>Prefer pass-by-reference-to-const over pass-by-value. It's typically more efficient and it avoids the slicing problem. </li>
	<li>The rule doesn't apply to built-in types and STL iterators and function object types. For them, pass-by-value is usually appropriate.</li>
</ol>
<p>When we debug the above code step by step, we'll realize we'll end up doing more objects copies in the pass-by-value case than pass-by-reference case.</p> 


<br /><br />
<img src="images/valuevsreference/MaeMoolDo.png" alt="MaeMoolDo"/>
<br /><br />


<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li> 
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />



<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
